/**
 * 用于出发连网操作的 action ，
 * 其结果根据需要，用dispatch({type: ...}) 的方式，
 * 通过redux对获取的数据进行本地化，即state保存和更新
 */
import * as dists from "../../service/index";
import Toast from 'react-native-root-toast';
export function create_service(name, ...params) {
  let promise = null
  try {
    promise = call_service(name, ...params)
  } catch (ex) {
    console.error(ex)
  }
  if (promise) return (dispatch) => { return dispatch_reducers(dispatch, promise, name, params); }
}
/**
 * 用于联网后　需要 reducer 保存　data　到　state
 */
function dispatch_reducers(dispatch, promise, name, params) {
  const nPromise =
    promise.then(data => {
      if (data.success) {
        dispatch({ type: name, requestParams: params, data: data.data });
        return data.data;
      } else {
        if (data.code == 'NO_LOGIN') {
          dispatch({ type: 'CLEAN_USER_INFO', data: { data: null } });
          Actions.replace('auth')
        } else {
          Toast.show(data.message, { position: Toast.positions.CENTER })
        }
      }
    }).catch(error => {
      console.log('%c create_service && catch error -->> ', 'color:red', error);
    })
  return nPromise
}
function call_service(name, ...params) {
  if (!dists[name]) {
    throw 'dist service ' + name + " undefined."
  }
  return dists[name].apply(null, params)
}
